//
//  DefaultSubscription.m
//  QiYReader
//
//  Created by 奇阅科技 on 15/3/2.
//  Copyright (c) 2015年 奇阅科技. All rights reserved.
//

#import "DefaultSubscription.h"
#import "BookReadPermissions.h"
#import "ZMYLKDB.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "SIDownloadManager.h"
#import "SIBreakpointsDownload.h"
#import "ZMYNetWorkAPI.h"
@interface DefaultSubscription ()
{
    NSMutableString *allChapterIDs;
}
@property (weak,nonatomic)MBProgressHUD *progressHud;
@end
@implementation DefaultSubscription
-(instancetype)init{
    self = [super init];
    if (self) {
        self = [[[NSBundle mainBundle]loadNibNamed:@"DefaultSubscription" owner:nil options:nil]lastObject];
    }
    return self;
}

-(void)beginVerificationReadPermissionsSucceed:(void(^)(void))succeedRefresh Fail:(void(^)(void))failRefresh Cancel:(void(^)(void))cancelRefresh{
    [AppDelegate hideAllHUD:[AppDelegate delegate].window];
    if (self.chapterIds==nil||self.chapterIds.count<2) {
        failRefresh();
        return;
    }
    self.succeedSubscription = succeedRefresh;
    self.failSubscription = failRefresh;
    self.cancelSubscription = cancelRefresh;
    
    [self.progressHud show:YES];
    [self.progressHud setProgress:0.1];
    
    //开始进行权限验证，查看本地是否有阅读权限
    
    if ([[self.chapterIds objectAtIndex:0]isEqualToString:[self.chapterIds lastObject]]) {
        BookReadPermissions *readPer = [BookReadPermissions new];
        readPer.articleid = self.book.articleid;
        readPer.chapterId = self.chapterIds.lastObject;
        allChapterIDs = [NSMutableString stringWithString:readPer.chapterId];
        if (![readPer getMyReadPermissions]) {
            //如果本地没有阅读权限
            [self.progressHud setProgress:0.1];
            [self getMyReadPermissions:allChapterIDs];
        }else{
            [self.progressHud setProgress:0.6];
            //本地有阅读权限，检查是否有章节内容
            [self bookChapterTextVerification];
        }
    } else {
        BOOL isAllPermissions = YES;//是否所有章节本地都有阅读权限
        for (NSString *chapterId in self.chapterIds) {
            BookReadPermissions *readPer = [BookReadPermissions new];
            readPer.articleid = self.book.articleid;
            readPer.chapterId = chapterId;
            if (![readPer getMyReadPermissions]) {
                //如果本地没有阅读权限
                isAllPermissions = NO;
            }
            //拼接这组章节ID
            if (!allChapterIDs) {
                allChapterIDs = [[NSMutableString alloc] initWithString:chapterId];
            } else {
                [allChapterIDs appendFormat:@",%@",chapterId];
            }
        }
        if (!isAllPermissions) {
            //如果本地没有阅读权限
            [self.progressHud setProgress:0.1];
            [self getMyReadPermissions:allChapterIDs];
        }else{
            [self.progressHud setProgress:0.6];
            //本地有阅读权限，检查是否有章节内容
            [self bookChapterTextVerification];
        }
    }
    
}
-(void)getMyReadPermissions:(NSString *)chapterId{
#pragma mark 请求服务器阅读权限
    [[ZMYNetWorkAPI default]getDownloadChapterPermission:chapterId Book:self.book Response:^(NSDictionary *resultDic) {
        NSInteger ret = [[resultDic objectForKey:@"ret"] integerValue];
        switch (ret) {
            case 200:{//可以阅读,去验证章节内容是否存在
                [self.progressHud setProgress:0.6];
                NSDictionary *dict = [resultDic objectForKey:@"body"];
                NSArray *autosub_chapters = [dict objectForKey:@"autosub_chapters"];
                [self updateBookReadPermissionsYES:autosub_chapters];
                [self bookChapterTextVerification];
                break;
            }
            case 1:{
                self.progressHud.progress = 0;
                [self.progressHud hide:YES];
                [AppDelegate showAlert:nil message:@"请登录后继续操作"];
                self.failSubscription();
                break;
            }
            case 203:{//章节未订阅，去申请扣费
                [self.progressHud setProgress:0.2];
                NSDictionary *dict = [resultDic objectForKey:@"body"];
                NSArray *autosub_chapters = [dict objectForKey:@"autosub_chapters"];
                NSArray *allChapters = [allChapterIDs componentsSeparatedByString:@","];
                NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",autosub_chapters];
                
                NSArray * filter = [allChapters filteredArrayUsingPredicate:filterPredicate];
                [self updateBookReadPermissionsYES:filter];
                [self chargeForChapters:allChapterIDs];
                break;
            }
            default:{
                self.progressHud.progress = 0;
                [self.progressHud hide:YES];
                [AppDelegate showAlert:nil message:@"网络请求失败，请稍后再试"];
                self.failSubscription();
                break;
            }
                break;
        }
    } error:^(NSString *errorStr) {
        self.progressHud.progress = 0;
        [self.progressHud hide:YES];
        [AppDelegate showAlert:nil message:errorStr];
        self.failSubscription();
    }];
}
-(MBProgressHUD *)progressHud{
    if (!_progressHud) {
        _progressHud = [MBProgressHUD showHUDAddedTo:[AppDelegate delegate].window animated:YES];
        self.progressHud.removeFromSuperViewOnHide = YES;
        self.progressHud.dimBackground = YES;
        self.progressHud.mode = MBProgressHUDModeDeterminate;
        self.progressHud.detailsLabelText = @"加载中...";
        self.progressHud.removeFromSuperViewOnHide=YES;
    }
    return _progressHud;
}
#pragma mark 章节扣费
-(void)chargeForChapters:(NSString *)autosub_chapters{
    
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        //用户未登录
        [AppDelegate showAlert:nil message:@"本章节是VIP章节，请登录后继续操作"];
        self.failSubscription();
        return;
    }
    if (user.auto_subscription) {
        //如果是自动订阅，就去申请扣费
        [self.progressHud setProgress:0.4];
        [self chargeForChaptersNetwork:autosub_chapters];
    } else {
        [self showWebView];
    }
    
}
-(void)showWebView{
    self.progressHud.progress = 0;
    [self.progressHud hide:YES];
    UserAccount *user = [UserAccount currentAccount];
    //md5(md5（用户ID.时间戳.加密密匙).加密密匙)
    NSString *time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
    NSString *auth = [[[NSString stringWithFormat:@"%@%@",[[NSString stringWithFormat:@"%@%@%@",user.uid,time,PRIVATE_KEY] md5],PRIVATE_KEY] md5] substringToIndex:10];
    NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    NSString *webUrl = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=pay_chapter_multiple_order&chapterids=%@&articleid=%@&v=%@&uid=%@&token=%@&t=%@&auth=%@&srcid=iOS&ct=iOS&pay_way=iOS&pt=client",SERVER,allChapterIDs,self.book.articleid,currentAppVersion,user.uid,user.token,time,auth];
    self.webUrl = webUrl;
    [self showView];
}
-(void)chargeForChaptersNetwork:(NSString *)chapters{
    //请求扣费
    [[ZMYNetWorkAPI default]getDownloadChargeForChapters:chapters Book:self.book Response:^(NSDictionary *resultDic) {
        NSInteger ret = [[resultDic objectForKey:@"ret"] integerValue];
        switch (ret) {
            case 200:{//可以下载
                [self.progressHud setProgress:0.6];
                [self updateBookReadPermissionsYES:self.chapterIds];
                [self bookChapterTextVerification];
                break;
            }
            case 1:{
                [AppDelegate showAlert:nil message:@"请登录后继续操作，请登录后继续操作"];
                self.failSubscription();
                break;
            }
                
            case 202:{//余额不够
//                [[ZMYNetWorkAPI default]cancelAllPermissionNetworkOperation];
//                [[ZMYNetWorkAPI default]cancelAllChargeNetworkOperation];
                [self showWebView];
                break;
            }
            default:{
                [AppDelegate showAlert:nil message:@"网络请求失败，请稍后再试"];
                self.failSubscription();
                break;
            }
                break;
        }
        
    } error:^(NSString *errorStr) {
        [AppDelegate showAlert:nil message:errorStr];
        self.failSubscription();
    }];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlString = [[request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if([urlComps count]==2 && [[urlComps objectAtIndex:0] isEqualToString:@"ios"])
    {
        NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex:1] componentsSeparatedByString:@"/omituofo"];
        if (arrFucnameAndParameter.count==1) {
            if ([arrFucnameAndParameter[0] hasPrefix:@"ReadPackage"]) {
                return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
            } else if ([arrFucnameAndParameter[0] isEqualToString:@"Lack_of_balance"]) {
                return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"login"]){
                [AppDelegate showHUDAndHide:@"请登录后继续操作" view:[AppDelegate delegate].window];
                return NO;
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"getnull"]){
                [AppDelegate showHUDAndHide:@"信息获取失败" view:[AppDelegate delegate].window];
                return NO;
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"nopay"]){
                [AppDelegate showHUDAndHide:@"没有需要支付的信息 " view:[AppDelegate delegate].window];
                return NO;
            }
        }else if (arrFucnameAndParameter.count==2) {
            if([[arrFucnameAndParameter objectAtIndex:0] isEqualToString:@"PayChapters"]){
                NSURL *url = [NSURL URLWithString:[[NSString alloc]initWithData:[[NSData alloc]initWithBase64EncodedString:arrFucnameAndParameter[1] options:0] encoding:NSUTF8StringEncoding]];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
                request.HTTPMethod = @"GET";
                // 章节支付URL
                NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
                
                // 官方验证结果为空
                if (result == nil) {
                    [AppDelegate showHUDAndHide:@"订阅章节失败，请重试" view:[AppDelegate delegate].window];
                    return NO;
                }
                
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
                if ([[dict objectForKey:@"ret"] isEqualToString:@"200"]||[[dict objectForKey:@"ret"] isEqualToString:@"202"]) {
                    [AppDelegate showHUDAndHide:@"订阅章节订阅成功" view:[AppDelegate delegate].window];
                    NSArray *autosub_chapters = [[dict objectForKey:@"body"] objectForKey:@"chapterIds"];
                    [self updateBookReadPermissionsYES:autosub_chapters];
                    [super closeView:nil];
                    [self.progressHud setProgress:0.6];
                    [self.progressHud show:YES];
                    [self bookChapterTextVerification];
                    return NO;
                }else{
                    [super closeView:nil];
                    [AppDelegate showAlert:nil message:@"订阅章节订阅失败，请重试"];
                    self.failSubscription();
                    return NO;
                }
                
            }else if([[arrFucnameAndParameter objectAtIndex:0] isEqualToString:@"sub_list_texts"]){
                [super closeView:nil];
                [self.progressHud setProgress:0.4];
                [self.progressHud show:YES];
                
                [self chargeForChaptersNetwork:allChapterIDs];
                return NO;
            }
        }
        [AppDelegate showHUDAndHide:@"网络错误，请稍后再试" view:[AppDelegate delegate].window];
        return NO;
    }
    if ([urlComps count]==2) {
        if ([[urlComps objectAtIndex:0] isEqualToString:@"http"]) {
            return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
        }
        
    }
    return NO;
}
- (IBAction)closeView:(id)sender{
    [super closeView:sender];
    self.cancelSubscription();
}
#pragma mark 判断本地是否有章节内容
-(void)bookChapterTextVerification{
    if ([[self.chapterIds objectAtIndex:0]isEqualToString:[self.chapterIds lastObject]]) {
        if ([[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:allChapterIDs]) {
            //判断本地是否有该章节内容
            [self.progressHud setProgress:1];
            [self.progressHud hide:YES];
            self.succeedSubscription();
            [super closeView:nil];
        }else{
            [self.progressHud setProgress:0.7];
            //如果本地没有该章节内容
            [self downloadChapterText];
        }
    }else {
        for (NSString *chapterId in self.chapterIds) {
            if (![[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:chapterId]) {
                [self.progressHud setProgress:0.7];
                //如果本地没有该章节内容
                [self downloadChapterText];
                return;
            }
        }
        //判断本地是否有所有章节内容
        [self.progressHud setProgress:1];
        [self.progressHud hide:YES];
        self.succeedSubscription();
        [super closeView:nil];
    }
    
}
-(void)downloadChapterText{
#pragma mark 下载章节内容
    __weak typeof(self) weakSlef = self;
    NSString *purviewMark = [[NSString stringWithFormat:@"%@%@",[self.chapterIds objectAtIndex:0],self.chapterIds.lastObject] md5];
    purviewMark = [[NSString stringWithFormat:@"qy_%@",purviewMark] md5];
    NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=download_articleid&purviewMark=%@&chapterids=%@&output=txt&ct=iOS&v=%@&srcid=iOS",SERVER,purviewMark,allChapterIDs,currentAppVersion];
    NSString *downloadPath = [[PathHelper cacheDirectoryPathWithName:@"Lib"]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@%@",self.book.articleid,[self.chapterIds objectAtIndex:0],self.chapterIds.lastObject]];
    SIDownloadManager *siDownloadManager = [SIDownloadManager sharedSIDownloadManager];
    [siDownloadManager  addDownloadFileTaskInQueue:urlStr toFilePath:downloadPath breakpointResume:YES rewriteFile:NO DidComplete:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            if ([[ZMYLKDB getLKDBHelper]unarchiveFreeChapter:downloadPath Book:weakSlef.book]) {
                [weakSlef.progressHud setProgress:1];
                [weakSlef.progressHud hide:YES];
                weakSlef.succeedSubscription();
                [super closeView:nil];
            }else{
                [weakSlef.progressHud setProgress:1];
                [weakSlef.progressHud hide:YES];
                [AppDelegate showAlert:nil message:@"章节下载失败，请稍后再试"];
                weakSlef.failSubscription();
            }
        }
    } Progress:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, double paramProgress) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            [weakSlef.progressHud setProgress:paramProgress*0.2+0.8];
        }
    } Error:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, NSError *paramError) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            NSLog(@"%@ withError:%@",paramOperation.url,paramError.localizedDescription);
            [weakSlef.progressHud setProgress:0];
            [weakSlef.progressHud hide:YES];
            [AppDelegate showAlert:nil message:paramError.localizedDescription];
            weakSlef.failSubscription();
        }
        
    }];
}
-(void)updateBookReadPermissionsYES:(NSArray *)chapterIDArray{
    if (chapterIDArray.count<1) {
        return;
    }
    UserAccount *user = [UserAccount currentAccount];
    NSString *uid;
    if (user) {
        uid = user.uid;
    } else {
        uid = @"love";
    }
    for (NSString *chapterIDStr in chapterIDArray) {
        BookReadPermissions *readPer = [BookReadPermissions new];
        readPer.articleid = self.book.articleid;
        readPer.uid = uid;
        readPer.chapterId = chapterIDStr;
        readPer.readPermissions = YES;
        [readPer updateBookReadPermissions];
    }
    
}

@end
